/**
 * All Rights Reserved , Copyright (C) 2023 , 青岛鼎信通讯股份有限公司
 * <p>
 * QemDutyDeptService
 * 维护-责任主体部门配置
 * <p>
 * 修改纪录
 * 2023-01-06 版本：1.0 xinfushuo 创建。
 *
 * @version 版本：1.0
 * @author 作者：xinfushuo
 * 创建日期：2023-01-06
 */
package com.topscomm.qem.service.impl;

import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.cbo.pojo.CboUserEntity;
import com.topscomm.cbo.service.impl.CboUserService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.qem.pojo.QemDutyDeptEntity;
import com.topscomm.tap.common.DatacodeCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.topscomm.qem.service.IQemDutyDeptService;
import com.topscomm.qem.service.impl.auto.QemDutyDeptServiceAuto;

import java.util.*;
import java.util.stream.Collectors;

@Service(value = "qemDutyDeptService")
@Scope(value = "singleton")
public class QemDutyDeptService extends QemDutyDeptServiceAuto implements IQemDutyDeptService {

    @Autowired
    CboUserService cboUserService;

    @Override
    public void setDispFields(Map<String, Object> mapRow, DatacodeCache datacodeCache) {
        super.setDispFields(mapRow, datacodeCache);
        // 获取创建用户的信息
        if (mapRow.get(QemDutyDeptEntity.FieldCreateuser) != null) {
            String createUserId = ConvertUtil.convertToString(mapRow.get(QemDutyDeptEntity.FieldCreateuser));
            CboUserEntity userEntity = cboUserService.queryById(createUserId);
            mapRow.put("createusername", userEntity.getName());
        }
        // 获取修改用户的信息
        if (mapRow.get(QemDutyDeptEntity.FieldModifieduser) != null) {
            String createUserId = ConvertUtil.convertToString(mapRow.get(QemDutyDeptEntity.FieldModifieduser));
            CboUserEntity userEntity = cboUserService.queryById(createUserId);
            mapRow.put("modifiedusername", userEntity.getName());
        }
    }

    /**
     * @author: caozhiyuan
     * @date: 2023-01-06 16:13:36
     * @param: entity
     * @description: 插入前
     * @return: void
     * @modify:
     */
    @Override
    protected void beforeInsert(BasicEntity entity) throws ServiceException {
        super.beforeInsert(entity);
        Map<String, Object> map = new HashMap<>();
        // 插入前校验封装数据
        map.put(QemDutyDeptEntity.FieldCode, entity.getValue(QemDutyDeptEntity.FieldCode));
        map.put(QemDutyDeptEntity.FieldName, entity.getValue(QemDutyDeptEntity.FieldName));
        this.checkRepeat(map);
    }

    /**
     * @author: caozhiyuan
     * @date: 2023-01-06 16:13:51
     * @param: map
     * @description: 更新前
     * @return: void
     * @modify:
     */
    @Override
    protected void updateBefore(Map<String, Object> map) throws ServiceException {
        super.updateBefore(map);
        this.checkRepeat(map);
    }

    /**
     * @author: caozhiyuan
     * @date: 2023-01-06 16:16:44
     * @param: map 校验参数
     * @description: 校验重复的配置添加
     * @return: void
     * @modify:
     */
    private void checkRepeat(Map<String, Object> map) {
        // 唯一校验可通过平台的唯一控制进行控制，这里进行了手动的控制
        StringBufferProxy sql = new StringBufferProxy();
        // 禁止添加编号或名称重复的配置。
        sql.appendSingle("(code = '{0}' or name = '{1}')",
                map.get(QemDutyDeptEntity.FieldCode),
                map.get(QemDutyDeptEntity.FieldName));
        // 如果是编辑，则排除对应id的数据
        if (map.containsKey(QemDutyDeptEntity.FieldId)) {
            sql.appendSingle(" and id != '{0}'", map.get(QemDutyDeptEntity.FieldId));
        }
        List<QemDutyDeptEntity> tempList = queryByWhere(ConvertUtil.convertToString(sql));
        if (tempList.size() > 0) {
            throw new ServiceException("请勿重复添加相同编号或名称的配置！");
        }
    }

    /**
     * @author: caozhiyuan
     * @date: 2023-01-10 17:19:14
     * @param: paraMap
     * @description: 根据责任主体部门编号获取质量运营专员
     * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @modify:
     */
    @Override
    public Map<String, Object> getUsersByCode(Map<String, Object> paraMap) {
        // 获取责任主体部门编号
        String code = ConvertUtil.convertToString(paraMap.get("qry_code"));
        if (StringUtil.isEmpty(code)) {
            throw new ServiceException("参数有误");
        }
        StringBufferProxy sql = new StringBufferProxy();
        // 根据编号查询责任主体部门。
        sql.appendSingle("code = '{0}'", code);
        QemDutyDeptEntity qemDutyDeptEntity = this.queryObjectByWhere(sql.toString());
        if (qemDutyDeptEntity == null) {
            throw new ServiceException("未查询到责任主体部门配置");
        }
        // 返回参数用户code和name
        List<String> userCodes = new ArrayList<>();
        List<String> userNames = new ArrayList<>();
        // 获取质量运营部门
        if (!StringUtil.isEmpty(qemDutyDeptEntity.getDeptcodes())) {
            List<String> deptCodeList = Arrays.asList(qemDutyDeptEntity.getDeptcodes().split(","));
            // 条件sql拼接
            if (deptCodeList.size() > 0) {
                String deptstr = deptCodeList.stream().map(item -> "'" + item + "'").collect(Collectors.joining(","));
                sql.clear();
                // 查询当前质量运营部门下直属的所有人，排除离职人员，EXTENDFIELD1 用来标识用户是否为自然人以及在职员工的
                sql.appendSingle(" deptid in (select id from cbodept where code in ({0})) and EXTENDFIELD1 IS NOT NULL AND ENABLED = 1", deptstr);
                List<CboUserEntity> cboUserEntitieList = cboUserService.queryByWhere(sql.toString());
                for (CboUserEntity cboUserEntity : cboUserEntitieList) {
                    userCodes.add(cboUserEntity.getCode());
                    userNames.add(cboUserEntity.getName());
                }
            }
        }
        // 拼接质量运营专员
        String qcuserCodes = qemDutyDeptEntity.getQcusercodes();
        String qcuserNames = qemDutyDeptEntity.getQcusernames();
        if (!StringUtil.isEmpty(qcuserCodes)) {
            for (String temp : Arrays.asList(qcuserCodes.split(","))) {
                userCodes.add(temp);
            }
            for (String temp : Arrays.asList(qcuserNames.split(","))) {
                userNames.add(temp);
            }
        }
        // 返回数据去重与封装
        Map<String, Object> data = new HashMap<>();
        String responseUserCodes = String.join(",", userCodes.stream().distinct().collect(Collectors.toList()));
        String responseUsernames = String.join(",", userNames.stream().distinct().collect(Collectors.toList()));
        data.put("usercodes", responseUserCodes);
        data.put("usernames", responseUsernames);
        return data;
    }

    /**
     * @author: caozhiyuan
     * @date: 2023-01-11 10:16:40
     * @description: 获取当前用户拥有权限的责任主体部门，以英文逗号分割
     * @return: java.util.List<java.lang.String>
     * @modify:
     */
    @Override
    public List<String> getAuthorizationByActiveUser() {
        // 获取当前用户信息
        String userCode = getSessionUserBean().getUser().getCode();
        String userDeptCode = getSessionUserBean().getDept().getCode();
        // 拥有权限的责任主体部门的code
        List<String> dutyDeptCodes = new ArrayList<>();
        // 查询所有生效的责任主体部门
        List<QemDutyDeptEntity> qemDutyDeptEntityList = this.queryByWhere("ENABLED = 1");
        for (QemDutyDeptEntity qemDutyDeptEntity : qemDutyDeptEntityList) {
            // 判断授权人员
            if (!StringUtil.isEmpty(qemDutyDeptEntity.getAuthorizercodes())) {
                List<String> authorizerCodes = Arrays.asList(qemDutyDeptEntity.getAuthorizercodes().split(","));
                // 拥有权限
                if (authorizerCodes.contains(userCode)) {
                    dutyDeptCodes.add(qemDutyDeptEntity.getCode());
                    continue;
                }
            }
            // 判断授权部门
            if (!StringUtil.isEmpty(qemDutyDeptEntity.getAuthorizationdeptcodes())) {
                List<String> authorizationDeptCodes = Arrays.asList(qemDutyDeptEntity.getAuthorizationdeptcodes().split(","));
                // 三种判断是否拥有权限的情况
                for (String authorizationDeptCode : authorizationDeptCodes) {
                    // 1、和当前判断授权部门编号相同，为直属授权部门
                    if (authorizationDeptCode.equals(userDeptCode)) {
                        dutyDeptCodes.add(qemDutyDeptEntity.getCode());
                        break;
                    }
                    // 2、用户的直属部门为授权部门子部门，则为被授权部门下的子部门的权限。如用户为D101，授权为D1
                    if (userDeptCode.length() > authorizationDeptCode.length()) {
                        // 如果用户直属部门以授权部门为前缀开始，则用户为被授权部门的子部门
                        if (userDeptCode.startsWith(authorizationDeptCode)) {
                            dutyDeptCodes.add(qemDutyDeptEntity.getCode());
                            break;
                        }
                    }
                    // 3、如果用户的直属部门比所判断的授权部门长度短，例如用户为D101，授权为D10101，则为仅授权给子部门，不给予权限
                }
            }
        }
        // 对责任主体部门去重
        dutyDeptCodes = dutyDeptCodes.stream().distinct().collect(Collectors.toList());
        return dutyDeptCodes;
    }
}
